import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './Test.less';

const FormItem = Form.Item;
const { Step } = Steps;

const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.ruleTest,
}))
@Form.create()
class TradeList extends PureComponent {
  state = {
    dataTradeList: {},
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    textLoading: false,
    formValues: {
      stockId: '',
      orderField: '', // 排序字段
      orderType: 0, // 排序方向
    }, // 查询菜单栏   查询参数
    textboxValues: {
      key: '',
      type: 1,
    },
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},
    suggestions: [],
  };

  columns = [
    {
      title: '股票代码',
      dataIndex: 'stockId',
    },
    {
      title: '序号',
      dataIndex: 'indexId',
    },

    {
      title: '财报时间 ',
      dataIndex: 'earningsDate',
      sorter: true,
    },
    {
      title: '涨跌幅%',
      dataIndex: 'changeRate',
      sorter: true,
    },
    /*    {
      title: '涨跌幅日期',
      dataIndex: 'changeRateDate',
    }, */
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      rule: { data2, filterData },
      loading,
      total,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: data2.list != undefined ? data2.list.fundEarningDateChangeRateModels : [],
      pagination: data2.pagination,
    };
    return (
      <PageHeaderWrapper title="个股财报日历史涨跌幅列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListForm}>{this.renderAdvancedForm({ data2 })}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={newdata}
              columns={this.columns}
              pagination={false}
              onChange={this.handleStandardTableChange}
              rowKey="id"
              bordered
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, listLoading } = this.state;
    document.body.addEventListener('keyuo', e => {
      if (window.event) {
        e = window.event;
      }
      const code = e.chaarCode || e.keycode;
      if (code === 13) {
        this.handleSearch();
      }
    });
  }

  componentWillMount() {
    document.body.removeEventListener('keyup', () => {});
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {
      dispatch,
      rule: { data2 },
    } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    if (data2.pagination.total == undefined) return;
    formValues.stockId = data2.list.fundEarningDateChangeRateModels[0].stockId;
    formValues.pageNum = 1;
    formValues.pageSize = 100;

    if (sorter.field) {
      // 排序参数
      formValues.orderField = `${sorter.field}`;
      if (sorter.order == 'ascend') {
        formValues.orderType = 2; // 升序
      } else if (sorter.order == 'descend') {
        formValues.orderType = 1; // 降序
      } else {
        formValues.orderType = 0; // 不排序
      }
    } else {
      formValues.orderField = '';
      formValues.orderType = 0; // 不排序
    }
    const params = {
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'rule/GetEarningDateChangeRateList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={14} sm={24}>
            {/*            <FormItem label="股票代码">
              {getFieldDecorator('stockId')(
                <Input placeholder="请输入" />
              )}
            </FormItem> */}

            <FormItem label="股票代码">
              {getFieldDecorator('stockId')(
                <Select
                  showSearch
                  style={{ width: '100%' }}
                  placeholder="请输入股票代码"
                  // maxTagCount={100}
                  // onChange={this.handleChange}
                  onSearch={this.onSearch.bind(this)}
                  onSelect={this.onSelect.bind(this)}
                >
                  {this.state.suggestions}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={10} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              {/*              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button> */}
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm(param = {}) {
    const {
      form: { getFieldDecorator },
    } = this.props;
    if (param.data2.list == undefined) {
      param.data2.list = {
        maxValue: '',
        meanValue: '',
        meanValueOfFall: '',
        meanValueOfRise: '',
        medianValue: '',
        medianValueOfFall: '',
        medianValueOfRise: '',
        minValue: '',
        nextEarningsDate: '',
        winRate: '',
        marketValue: '',
        fundEarningDateChangeRateModels: [],
      };
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 4, lg: 24, xl: 48 }}>
          <Col md={4} sm={24}>
            <FormItem label="均值">{param.data2.list.meanValue}</FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="最大涨幅 ">{param.data2.list.maxValue}</FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="涨的均值">{param.data2.list.meanValueOfRise}</FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="涨的中位数">{param.data2.list.medianValueOfRise}</FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="胜率">{param.data2.list.winRate}</FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 4, lg: 24, xl: 48 }}>
          {/*          <Col md={8} sm={24}>
            <FormItem label="下个财报时间">
              {param.data2.list.nextEarningsDate}
            </FormItem>
          </Col> */}

          <Col md={4} sm={24}>
            <FormItem label="中位数">{param.data2.list.medianValue}</FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="最大跌幅">{param.data2.list.minValue}</FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="跌的均值">{param.data2.list.meanValueOfFall}</FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="跌的中位数">{param.data2.list.medianValueOfFall}</FormItem>
          </Col>

          <Col md={5} sm={24}>
            <FormItem label="市值">{param.data2.list.marketValue}</FormItem>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { formValues, listLoading } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.state.formValues.stockId = values.stockId;
    });
    if (this.state.formValues.stockId != undefined) {
      this.setState({
        listLoading: true,
      });
      dispatch({
        type: 'rule/GetEarningDateChangeRateList',
        payload: formValues,
        callback: () => {
          this.setState({
            listLoading: false,
          });
        },
      });
    } else {
      message.warning('股票代码不能为空！');
    }
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.maxEarningsDate = '';
    formValues.minBreakEvenMargin = 0;
    formValues.minEarningsDate = '';
    formValues.minRoyalty = 0;
    formValues.minYieldRate = 0;

    dispatch({
      type: 'rule/GetRoyaltiesList',
      payload: formValues,
    });
  };

  onSearch(value) {
    /*    const {
      rule: {filterData},
    } = this.props; */
    const { textboxValues, textLoading, suggestions } = this.state;
    this.state.textboxValues.key = value;
    const _this = this;
    // this.state.suggestions=[];
    if (value.length > 0) {
      this.props.dispatch({
        type: 'rule/GetTextBoxList',
        payload: textboxValues,
        callback: () => {
          const suggestionsData = [];
          for (let i = 0; i < _this.props.rule.filterData.list.length; i++) {
            suggestionsData.push(
              <Option key={_this.props.rule.filterData.list[i].address}>
                {_this.props.rule.filterData.list[i].value}
              </Option>
            );
          }
          _this.setState({
            suggestions: suggestionsData,
          });
        },
      });
    }
  }

  onSelect(value) {
    const { dispatch, form } = this.props;
    const { formValues, listLoading } = this.state;

    if (this.state.formValues.stockId != undefined) {
      this.setState({
        listLoading: true,
      });
      dispatch({
        type: 'rule/GetEarningDateChangeRateList',
        payload: {
          stockId: value,
        },
        callback: () => {
          this.setState({
            listLoading: false,
          });
        },
      });
    } else {
      message.warning('股票代码不能为空！');
    }
  }
}

export default TradeList;
